package com.my.juc.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/6 16:58
 */

class MyTask extends RecursiveTask<Integer>{

    // 拆分差值不能超过10，计算10以内的运算
    private static final Integer VALUE = 10;
    private int begin; // 拆分开始值
    private int end; // 拆分结束值
    private int result; // 返回结果
    
    // 创建有参构造
    public MyTask(int begin, int end){
        this.begin = begin;
        this.end = end;
    }
    
    // 拆分和合并过程
    @Override
    protected Integer compute() {
        // 判断是否小于等于10
        if (end - begin <= VALUE){
            // 相加
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        }else {
            //进一步进行拆分
            // 获取中间值
            int mid = (begin + end) / 2;
            // 拆分左边
            MyTask task01 = new MyTask(begin, mid);
            // 拆分右边
            MyTask task02 = new MyTask(mid + 1, end);
            // 调用方法拆分
            task01.fork();
            task02.fork();
            // 合并结果
            result = task01.join() + task02.join();
        }
        return result;
    }
}

public class ForkJoinDemo {

    public static void main(String[] args) {
        // 创建MyTask对象
        MyTask myTask = new MyTask(0, 100);
        // 创建分支合并池对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        System.out.println("myTask.compute() = " + myTask.compute());
    }
    
}
